package com.tensquare.friend.service;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.dao.FriendDao;
import com.tensquare.friend.dao.NoFriendDao;
import com.tensquare.friend.enums.LikeEnum;
import com.tensquare.friend.pojo.Friend;
import com.tensquare.friend.pojo.NoFriend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class FriendService {

    @Autowired
    private FriendDao friendDao;

    @Autowired
    private NoFriendDao noFriendDao;

    @Autowired
    private UserClient userClient;

    /**
     * 删除好友
     *
     * @param userid
     * @param friendid
     */
    @Transactional
    public void deleteFriend(String userid, String friendid) {
        friendDao.deleteFriend(userid, friendid);
        friendDao.updateLike(friendid, userid, LikeEnum.ONE_SIDED_LIKE.getIslike());
        userClient.incFollowcount(userid, -1);
        userClient.incFanscount(friendid, -1);

        addNoFriend(userid, friendid);//向不喜欢的里面加入数据
    }

    /**
     * 增加不喜欢数据
     *
     * @param userid   用户ID
     * @param friendid 不被喜欢的用户ID
     * @Auther Tang
     */
    public void addNoFriend(String userid, String friendid) {
        NoFriend noFriend = new NoFriend();
        noFriend.setUserid(userid);
        noFriend.setFriendid(friendid);
        noFriendDao.save(noFriend);
    }


    /**
     * 新增朋友
     *
     * @param userid
     * @param friendid
     * @return
     */
    @Transactional
    public Integer addFriend(String userid, String friendid) {
        //判断用户是否已经关注了该人
        if (friendDao.selectCout(userid, friendid) > 0) {
            return 0;
        }
        //向对方表中添加数据
        Friend friend = new Friend();
        friend.setUserid(userid);
        friend.setFriendid(friendid);

        //判断用户是否被此人关注
        if (friendDao.selectCout(friendid, userid) > 0) {
            friend.setIslike(LikeEnum.MUTUAL_LIKING.getIslike());
            friendDao.updateLike(friendid, userid, LikeEnum.MUTUAL_LIKING.getIslike());
        } else {
            friend.setIslike(LikeEnum.ONE_SIDED_LIKE.getIslike());
        }
        userClient.incFanscount(friendid, 1);
        userClient.incFollowcount(userid, 1);
        friendDao.save(friend);
        return 1;
    }


}
